package sketch.metapost;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import sketch.doc.Sketch;
import sketch.ink.SampledPoint;
import sketch.ink.Stroke;

public class MPFile implements MPObject {

	private String fileName;

	private double u = 1;

	private List<MPCode> codes;

	public MPFile(String fileName) {
		this.fileName = fileName;
		codes = new ArrayList<MPCode>();
	}

	public void parse(Stroke stroke) {
		MPPolyLine pl = new MPPolyLine();

		for (SampledPoint sp : stroke.getPoints()) {
			pl.appendPoint(new MPPoint(sp));
		}

		appendCode(new MPDraw(pl));
	}

	public void appendCode(MPCode code) {
		codes.add(code);
	}


	public String getCode() {
		StringBuffer buf = new StringBuffer();
		buf.append("verbatimtex\n");
		buf.append("%&latex\n");
		buf.append("\\documentclass{article}\n");
		buf.append("\\usepackage{times}\n");
		buf.append("\\begin{document}\n");
		buf.append("etex\n\nbeginfig(1);\n");
		buf.append("  u = " + u + "pt;\n");

		for (MPCode code : codes) {
			buf.append("  " + code.getCode() + ";\n");
		}

		buf.append("endfig;\n");
		buf.append("verbatimtex\n");
		buf.append("\\end{document}\n");
		buf.append("etex\nend");

		return buf.toString();
	}

	public static void main(String[] args) {
		Sketch s = new Sketch();
		s.readFromFile(new File("rho-k.sample"));

		MPFile mp = new MPFile("rho-k-ink.mp");
		mp.parse(s.getStrokeById(0));
//		System.out.println(mp.getCode());
		mp.printFile();
	}

	public void printFile() {
		try {
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName))));

			bw.write(getCode());
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
